<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Models\Merchant;
use App\Models\Broker;
use App\Models\Machine;
use App\Models\MachineManager;
use App\Models\Role;
use App\Models\Auth;
use App\Http\Requests\Admin\AdminUserRequest;
use App\Models\UsersCode;
use Illuminate\Support\Facades\DB;
use App\Models\Jd;
use App\Events\Notice;


class MerchantController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, Merchant $merchant)
    {
        $manager = auth('admin')->user();
        if($manager->type == 2){
            $merchant = $merchant->where(['parent_id' => $manager->id]);
        }
        if($manager->type == 3){
            $merchant = $merchant->where('id',$manager->id);
        }
        $admin_users = $merchant->filter($request->all())->orderBy('id', 'desc')->paginate(config('api.page.limit'));
        $name = $request->name;
        $phone = $request->phone;
        return view('admins.merchant.index',compact('admin_users','name', 'phone'));
    }

    public function lists(Merchant $merchant,Broker $broker)
    {
        $user = auth('admin')->user();
        if($user->type == 2){
            $broker = $broker->where('id', $user->id)->orWhere('parent_id',$user->id)->select('id')->get();
            $ids = $broker->pluck('id')->toArray();
            $merchant = $merchant->whereIn('parent_id',$ids);
        }
        if($user->type == 3){
            $merchant = $merchant->where('id', $user->id);
        }
        $merchants = $merchant->orderBy('id', 'desc')->get();
        return json_encode(['code' => 200, 'msg' => 'success', 'data' => $merchants]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Broker $broker)
    {
        $manager = auth('admin')->user();
        if($manager->type == 2){
            $broker = $broker->where('id',$manager->id)->orWhere('parent_id', $manager->id);
        }    
        $brokers = $broker->get();
        return view('admins.merchant.add', compact('brokers'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(AdminUserRequest $request, Merchant $merchant)
    {
        // 开启事务
        DB::beginTransaction();
        // 数据处理
        try {
            $merchant = $merchant->create($request->all());
            if ( !$merchant ) {
                throw new \Exception("添加失败！");
            }
            $result = $merchant->UersCode()->create($request->all());
            if ( !$result) {
                throw new \Exception("添加失败！");
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('warning',$e->getMessage());
        }
        return redirect()->route('admin.merchants.index')->with('success', '添加成功');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Broker $broker, Merchant $merchant)
    {
        $manager = auth('admin')->user();
        if($manager->type == 2){
            $broker = $broker->where('id',$manager->id)->orWhere('parent_id', $manager->id);
        }   
        $brokers = $broker->get();
        $merchant->load('UersCode');
        $userscode = $merchant->UersCode;
        return view('admins.merchant.edit', compact('merchant', 'brokers', 'userscode'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(AdminUserRequest $request, Merchant $merchant, UsersCode $user_code)
    {
        // 开启事务
        DB::beginTransaction();
        // 数据处理
        try {
            $result1 = $merchant->update($request->all());
            if ( !$result1 ) {
                throw new \Exception("编辑失败！");
            }
            $data['customerNum'] = $request->input('customerNum');
            $data['shopNum'] = $request->input('shopNum');;
            $data['shopAccess'] = $request->input('shopAccess');;
            $data['shopSecret'] = $request->input('shopSecret');;
            $result = $user_code->where('merchant_id', $merchant->id)->update($data);
            if ( !$result) {
                throw new \Exception("编辑失败！");
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('warning',$e->getMessage());
        }
        return redirect()->route('admin.merchants.index')->with('success', '编辑成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    // public function destroy(Merchant $merchant)
    // {
    //     dd($merchant);
    // }
    public function delete(Request $request, Auth $auth, Merchant $merchant)
    {
        $manager = $auth->where('parent_id', $request->id)->first();
        $merchant = $merchant->with('machine')->find($request->id);
        if($merchant->machine->isNotEmpty() || $manager){
            return json_encode(['code' => 400, 'message' => '该账号下存在下级账户或设备,请移除后再删除']);
        }
        $merchant->delete();
        return json_encode(['code' => 200, 'message' => '删除成功']);
    }

    //分配设备
    public function allocation(Merchant $merchant)
    {
        return view('admins.merchant.allocation', compact('merchant'));
    }
    //
    public function allocationStore(Request $request, Merchant $merchant)
    {
        $merchant = $merchant->find($request->merchant_id);
        if(!$request->machines){
            $res = optional($merchant)->machine()->detach();
            return redirect()->route('admin.merchants.index')->with('success', '编辑成功');
        }
        $machine_ids = explode(',', $request->machines);
        $machine_manager_data = [];
        foreach ($machine_ids as $key => $value) {
            $machine_manager_data[$value] = ['type' => $merchant->type, 'percentage' => 0.06];
        }
        $res = optional($merchant)->machine()->sync($machine_manager_data);
        if(empty($res['attached'])){
            return redirect()->route('admin.merchants.index')->with('warning','编辑失败'); 
        }
        return redirect()->route('admin.merchants.index')->with('success', '编辑成功');
    }
    //获取设备
    public function machines(Request $request, Merchant $merchant, Machine $machine, MachineManager $machine_manager)
    {        
        $merchant_id = $request->merchant_id;
        $merchant = $merchant->with('parent')->find($merchant_id);
        if(optional($merchant->parent)->parent_id){
            $machines = $machine->whereHas('machine_managers', function($query) use ($merchant){
                $query->where('manager_id', $merchant->parent_id)->where('type','<>',3);
            })->get(); 
        }else{
           $machines = $machine->Has('machine_managers','=',1)->whereHas('machine_managers', function($query) use ($merchant){
                $query->where('manager_id', $merchant->parent_id);
            })->get(); 
        }
        //获取经销商的所有设备
        $broker_machines = $machine_manager->where('manager_id', $merchant->parent_id)->get();
        $broker_machines = $broker_machines->pluck('machine_id')->toArray();
        //获取当前经销商下的商户的所有设备
        $manager_machines = $machine_manager->where('manager_id',$merchant_id)->get();
        $merchant_machines = $manager_machines->pluck('machine_id')->toArray();
        $merchant_machines = array_intersect($merchant_machines,$broker_machines);
        $machines = $machines->merge($machine->whereIn('id', $merchant_machines)->get());
        return json_encode(['code' => 200, 'msg' => 'success', 'data' => compact('machines', 'merchant_machines')]);

    }

    public function setRole(Merchant $merchant)
    {
        return view('admins.merchant.setroles', compact('merchant'));
    }
    /**
     * [分配角色 description]
     * @param Request    $request    [description]
     * @param Role       $role       [description]
     * @param Permission $permission [description]
     */
    public function setRoleStore(Request $request, Role $role, Auth $merchant)
    {   
        $merchant_id = $request->merchant_id;
        $merchant = $merchant->with('roles')->find($merchant_id);
        $roles = $request->roles;
        if(!$roles){
            optional($merchant)->roles()->detach();   
        }else{
            $res =  optional($merchant)->assignRole(explode(',', $roles)); 
        }               
        return redirect()->route('admin.merchants.index')->with('success', '编辑成功');
    }

    public function getRoles(Request $request, Role $role, Auth $merchant)
    {
        $merchant_id = $request->merchant_id;
        $merchant = $merchant->with('roles')->find($merchant_id);
        $roles = $role->get();
        $merchant_roles = optional($merchant)->roles; 
        $merchant_roles = optional($merchant_roles)->pluck('id');
        return json_encode(['code' => 200, 'msg' => 'success', 'data' => compact('merchant_roles','roles')]);
    }
    //重置密码
    public function resetPassword(Request $request, Merchant $merchant)
    {
        $merchant = $merchant->find($request->id);
        $merchant->password = encrypt_str('123456');
        $res = $merchant->save();
        return json_encode(['code' => 200, 'msg' => 'success', 'data' => $res]);
    }
    //报单列表
    public function jdList(Request $request, Jd $jd)
    {
        $jds = $jd->with('merchant')->filter($request->all())->orderBy('id', 'desc')->paginate(config('api.page.limit'));
        $state = $request->state;
        $phone = $request->phone;
        return view('admins.merchant.jdlist',compact('jds', 'phone','state'));
    }


    //编辑报单
    public function jdedit($id, Jd $jd){
        $jd_info = $jd->with('merchant')->find($id);
        return view('admins.merchant.jdedit',compact('jd_info'));
    }
    //修改数据
    public function jdupdate($id, Request $request, Jd $jd, Auth $merchant)
    {
        $jd = $jd->find($id);
        $jd_info = $jd->update(['state' => $request->state,'opinion' => $request->opinion]);
        if($request->state == 3){
            event(new Notice($merchant->find($jd->uid)));
        }
        return redirect()->route('admin.merchants.jdList')->with('success', '审核成功');
    }
}
